package fastServer;


import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import protocol.Header;
import protocol.IOMessage;
import protocol.MessageType;

public class LoginAuthRespHandler extends ChannelInboundHandlerAdapter{

	private static Map<String, ChannelHandlerContext> nodecheck 
	      = new ConcurrentHashMap<String, ChannelHandlerContext>();
	
	public static Map<String, ChannelHandlerContext> userNode
	      = new ConcurrentHashMap<String, ChannelHandlerContext>();

	
	public LoginAuthRespHandler() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg){
		IOMessage message = (IOMessage) msg;

		System.out.println("server receive --> " + msg);
		
		// 如果是握手请求消息，处理，其它消息透传
		if (message.getHeader() != null
			&& message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
			
		    String nodeIndex = ctx.channel().remoteAddress().toString();
		    
		    System.out.println("remote IP --> " + nodeIndex);
		    
		    IOMessage loginResp = null;
		    // 重复登陆，拒绝
		    if (nodecheck.containsKey(nodeIndex)) {
			    System.out.println("重复登录， 拒绝 " + nodeIndex);
		    	loginResp = buildResponse(true, "");
		    } else {
			
		    InetSocketAddress address = (InetSocketAddress) ctx.channel()
				                            .remoteAddress();
			String ip = address.getAddress().getHostAddress();
			
			boolean isOK = false;
			JSONObject loginJson = JSON.parseObject(message.getBody());
			String username = loginJson.getString("username");
			String password = loginJson.getString("password");
			if(username.equals("friend_1") && password.equals("123"))isOK = true;
			if(username.equals("friend_2") && password.equals("123"))isOK = true;
			
			loginResp = buildResponse(isOK, username);
			if (isOK)
			    nodecheck.put(nodeIndex, ctx);
			    userNode.put(username, ctx);
			    System.out.println("登录成功 " +  username);
		    }
		    ctx.writeAndFlush(loginResp);
		    
		} else {
		    ctx.fireChannelRead(msg);
		}
	}
	
	private IOMessage buildResponse(boolean isOK, String username) {
		IOMessage message = new IOMessage();
		Header header = new Header();
		header.setType(MessageType.LOGIN_RESP.value());
		message.setHeader(header);
		
		if(isOK){
		
		JSONObject respJson = new JSONObject();
		respJson.put("username", username);
		respJson.put("login", "success");
		message.setBody(respJson.toJSONString());
		}else{
			
			JSONObject respJson = new JSONObject();
			respJson.put("login", "failure");
			respJson.put("username", username);
			message.setBody(respJson.toJSONString());
		} 
		return message;
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		//super.exceptionCaught(ctx, cause);
	}
}
